package com.lcxw.hxzbapi.controller.giftandcubecontroller;

import com.alibaba.fastjson.JSONObject;
import com.lcxw.hxzbapi.controller.membercontroller.MemberRealization;
import com.lcxw.hxzbapi.entity.pojo.GiftSend;
import com.lcxw.hxzbapi.entity.pojo.RichLevel;
import com.lcxw.hxzbapi.entity.pojo.YwpdMember;
import com.lcxw.hxzbapi.entity.requestBean.CubeGiftSendReq;
import com.lcxw.hxzbapi.entity.requestBean.GetGiftReceiveRecordReq;
import com.lcxw.hxzbapi.entity.response.GetGiftReceiveRecordResp;
import com.lcxw.hxzbapi.feign.adminFeignService.AdminService;
import com.lcxw.hxzbapi.service.GiftSendService;
import com.lcxw.hxzbapi.service.ProportionService;
import com.lcxw.hxzbapi.service.YwpdMemberService;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.Gift;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.GiftService;

@RestController
@RequestMapping("/api/gift")
@CrossOrigin
@Slf4j
public class GiftController {

    @Resource
    GiftSendService giftSendService;

    @Resource
    YwpdMemberService ywpdMemberService;

    @Resource
    GiftService giftService;

    @Resource
    GiftRealization giftRealization;

    @Resource
    MemberRealization memberRealization;

    @Resource
    AdminService adminService;

    @Resource
    ProportionService proportionService;

    /**
     * 获取所有礼物接口
     */
    @PostMapping("/getAll")
    public Response getAllGift(@RequestBody JSONObject requestParams) {

        Map<String, Object> data = new LinkedHashMap<>();
        List<Gift> giftList;

        try {
            giftList = giftService.selectAllEnableGift();
            int count = giftList.size();
            data.put("count", count);
            data.put("giftList", giftList);
        } catch (Exception e) {
            return Response.dbFail(log, "get all gift.");
        }

        return Response.ok(data);
    }


    /**
     * 礼物赠送接口
     */
    @PostMapping("/send")
    public Response sendGift(@RequestBody JSONObject requestParams) {
        long roomId = Long.parseLong(requestParams.getString("roomId"));
        long toUserId = Long.parseLong(requestParams.getString("toUserId"));
        long fromUserId = Long.parseLong(requestParams.getString("userId"));
        int giftId = Integer.parseInt(requestParams.getString("giftId"));
        int giftNum = Integer.parseInt(requestParams.getString("giftNum"));
        String source = requestParams.getString("source");

        try {
            //如果送礼成功，则返回值为0，否则返回值为送礼不足的金币数
            int sendResult = giftRealization
                .sendGift(roomId, toUserId, fromUserId, giftId, giftNum, source);
            if (0 == sendResult) {
                Integer consumeTotal = memberRealization.getConsumeTotal(fromUserId);
                RichLevel richLevel = memberRealization.getRichLevel(consumeTotal);

                //返回成功响应
                return Response.ok(richLevel);
            } else if (-1 == sendResult) {
                return Response.error(ErrorCode.INVALID_REQ, "背包里的礼物不足");
            } else {
                return Response
                    .common(log, "金币不足以送礼，还需" + sendResult + "金币", ErrorCode.INVALID_REQ,
                        "金币不足，还需" + sendResult + "金币", sendResult);
            }
        } catch (Exception e) {
            return Response.dbFail(log, "operate gift or giftSend");
        }
    }

    /**
     * 魔方抽奖券礼物赠送接口,即，赠送该礼物后，会有魔方的抽奖券
     */
    @PostMapping("/cubeGift/send")
    public Response cubeGiftSend(@RequestBody CubeGiftSendReq requestBody) {
        long roomId = Long.parseLong(requestBody.getRoomId());
        long fromUserId = Long.parseLong(requestBody.getUserId());
        long toUserId = Long.parseLong(requestBody.getToUserId());
        int giftId = Integer.parseInt(requestBody.getGiftId());
        int giftNum = Integer.parseInt(requestBody.getGiftNum());
        String source = requestBody.getSource();
        String cubeType = requestBody.getCubeType();

        JSONObject data = new JSONObject();

        int result;
        try {
            result = giftRealization
                .sendGift(roomId, toUserId, fromUserId, giftId, giftNum, source);
            //如果金币不足，则直接返回响应
            if (result != 0) {
                data.put("lack", result);
                return Response.common(log, "金币不足以送礼，还需" + result + "金币", ErrorCode.INVALID_REQ,
                    "金币不足，还需" + result + "金币", data);
            }

            //赠送魔方礼物后，需要给赠送者加魔方抽奖次数
            giftRealization.addTicket(fromUserId, giftNum, cubeType);

        } catch (Exception e) {
            return Response.dbFail(log, "礼物赠送记录操作");
        }
        int ticket = giftRealization.getTicketTimes(fromUserId, cubeType);

        data.put("ticket", ticket);
        return Response.ok(data);
    }


    /**
     * 礼物收取记录的查询接口
     */
    @PostMapping("/receive/getRecords")
    public Response getGiftReceiveRecords(
            @RequestBody GetGiftReceiveRecordReq getGiftReceiveRecordReq) throws ParseException {
        int pageNum = getGiftReceiveRecordReq.getPageNum();
        int pageSize = getGiftReceiveRecordReq.getPageSize();
        pageNum = (pageNum - 1) * pageSize;
        long userId = getGiftReceiveRecordReq.getUserId();

        int count = giftSendService.selectCountByUserId(userId);

        List<GiftSend> sendRecords = giftSendService
                .selectByUserIdWithPage(userId, pageNum, pageSize);

        List<GetGiftReceiveRecordResp> getGiftReceiveRecordRespList = new ArrayList<>();
        SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat simple3 = new SimpleDateFormat("MM-dd");
        for (GiftSend giftSend : sendRecords) {
            GetGiftReceiveRecordResp getGiftReceiveRecordResp = new GetGiftReceiveRecordResp();
            long fromUserId = giftSend.getFromUserId();
            int giftId = giftSend.getGiftId();
            YwpdMember ywpdMember = ywpdMemberService.selectYwpdMemberByUserId(fromUserId);
            Gift gift = giftService.selectByPrimaryKey(giftId);
            getGiftReceiveRecordResp.setMoney(StringUtil.formatDouble((gift.getNeedCoin()/10) * proportionService.getProp().getOrdinaryProp())+"");
            getGiftReceiveRecordResp.setUserName(ywpdMember.getUserName());
            getGiftReceiveRecordResp.setNickName(ywpdMember.getNickName());
            getGiftReceiveRecordResp.setImgUrl(ywpdMember.getImgUrl());
            getGiftReceiveRecordResp.setGiftName(gift.getGiftName());
            getGiftReceiveRecordResp.setGiftNum(giftSend.getGiftNum());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(sdf.parse(giftSend.getAddTime()));
            getGiftReceiveRecordResp.setAddTime(simple3.format(calendar.getTimeInMillis()));
            getGiftReceiveRecordResp.setGiftIcon(gift.getGiftIcon());
            getGiftReceiveRecordResp.setAge(ywpdMember.getAge());
            getGiftReceiveRecordResp.setSex(ywpdMember.getSex());
            getGiftReceiveRecordRespList.add(getGiftReceiveRecordResp);
        }
        JSONObject data = new JSONObject();
        data.put("total", count);
        data.put("giftReceiveRecordRespList", getGiftReceiveRecordRespList);
        return Response.ok(data);

    }
    /**
     * 礼物收取记录的查询接口
     */
    @PostMapping("/wall")
    public Response wall(@RequestBody JSONObject requestBody) throws Exception {
        return Response.ok(giftService.selectByUserId(requestBody.getLong("userId")));
    }
}
